package cn.com.controller;

import cn.com.beans.CollegeInfo;
import cn.com.beans.News;
import cn.com.service.NewsService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.xml.crypto.Data;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/insertNew")
public class InsertNewController {
    @Resource
    private NewsService newsService;

    @GetMapping
    public String home(){
        return "Insert/InsertNew";
    }


    @PostMapping
    @ResponseBody
    public Map<String,Object> insert(
            News news, Integer category,String title,String introduction,String author,String text,Integer pid,
            @RequestParam("file") MultipartFile file){


        Map<String,Object> result = new HashMap<>();
        if(file.isEmpty()){
            System.out.println("4");
            result.put("code",1);
            result.put("msg","文件为空，新增失败");
            return result;
        }else {
            String filename = file.getOriginalFilename();
            String filepath = "D:/IdeaWork/ExamWin/src/main/resources/static/files/images/";
            File dest = new File(filepath+filename);
            try {
                System.out.println(new Date());
                news.setCreatetime(new Date());
                news.setAuthor(author);
                news.setCategory(category);
                news.setIntroduction(introduction);
                news.setTitle(title);
                news.setText(text);
                news.setPid(pid);
                news.setReading(0);
                file.transferTo(dest);
                if (this.newsService.insert(news)) {
                    System.out.println("1");
                    result.put("code",0);
                    result.put("msg","新增成功");
                } else {
                    System.out.println("2");
                    result.put("code",1);
                    result.put("msg","新增失败");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.out.println("3");
            return result;
        }
    }
}
